<?php

namespace app\modules\weixin\controllers;

use app\common\components\BaseWebController;
use app\common\services\ConstantMapServices;
use app\common\services\StaticServices;
use app\common\services\UrlServices;
use app\common\services\UtilService;
use app\common\services\weixin\RequestService;
use app\models\activity\ActivityPrize;
use app\models\HongbaoLog;
use app\models\member\Member;
use app\models\StoreInformaction;
use app\models\YaojiangRecord;
use Yii;
use yii\base\Exception;
use yii\helpers\Json;
use yii\web\Response;

class ActivityController extends BaseWebController {
  public function actionIndex()
  {
    //        if (\Yii::$app->session->get('user_info')->open_id == 'oH5oJuN7v9H9-llplgNJLF3RElrM') {
    //            $result = $this->SetPrize('oH5oJuN7v9H9-llplgNJLF3RElrM', 177);
    //            var_dump($result);
    //            die;
    //        }

    if (Yii::$app->session->get('user_info')) {
      $js_info = RequestService::jsapi_ticket_config(RequestService::GetUrl(true));
      return $this->render('index', ['js_info' => $js_info]);
    } else {
      return $this->redirect(UrlServices::buildMUrl('/oauth/bind'));
    }
  }

  /**
   * 获取微信的JSDK
   * @return array
   */
  public function actionJsInfo()
  {
    if (Yii::$app->request->isPost) {
      $url = Yii::$app->request->post('url');
      Yii::$app->response->format = Response::FORMAT_JSON;
      $js_info = RequestService::jsapi_ticket_config($url);
      return ['code' => 200, 'data' => $js_info];
    }
  }

  /**
   * 验证是否可以摇奖
   * @return array
   */
  private function CheckPrize($open_id)
  {
    if (!UtilService::isWechat()) {
      return ['code' => -200, 'msg' => '请在微信中打开'];
    }
    if (!isset($open_id)) {
      return ['code' => -200, 'msg' => '系统正忙,请稍后再试试'];
    }

    $is_open = $this->get_curr_time_section(time());
    if ($is_open == 'no_begin') {
      return ['code' => -200, 'msg' => '214'];
    }
    if ($is_open == 'is_end') {
      return ['code' => -200, 'msg' => '212'];
    }
//    return ['code' => -200, 'msg' => '213'];
    //确认当前时间再哪个摇奖时间段中
    $time_area = date('H', time());
    $common_time_arr = StaticServices::timeArr();
    //查询中奖表
    $connection = YaojiangRecord::getDb();
    $transaction = $connection->beginTransaction();
    try {
      $act = ActivityPrize::tableName();
      // 判断是否有奖品可以抽
      $sql = "SELECT SUM(prize_num) as prize_count FROM {$act} FOR UPDATE";
      $command = $connection->createCommand($sql);
      $prize_count = $command->queryOne();
      if ($prize_count['prize_count'] == 0) {
        throw new Exception('213');
      }

      //验证用户是否中奖
      $member_info = Member::find()->where(['open_id' => $open_id])->one();
      if ($member_info->yaojiang_count == 1) {
        throw new Exception('215');
      }

      $yao = YaojiangRecord::tableName();
      //当前时间段中已经中出多少奖品
      $now_time = date('Y-m-d H', time()) . ':00:00';
      $now_time = strtotime($now_time);
      $end_time = $now_time + 3600;
      $sql = "SELECT count(*) as yaojiang_count FROM {$yao} WHERE create_time BETWEEN {$now_time} AND {$end_time} FOR UPDATE ";
      $command = $connection->createCommand($sql);
      $yaojiang_count = $command->queryOne();
      if ($common_time_arr[$time_area] - $yaojiang_count['yaojiang_count'] <= 0) {
        throw new Exception('213');
//        return ['code' => -200, 'msg' => '213'];          //此时间段奖品已经全部抽完
      }

      //获取ip如果出现多次，直接踢
      $ip = UtilService::getIP();
      $count = YaojiangRecord::find()->where(['ip' => $ip])->count();
      if (intval($count) >= 10) {
        throw new Exception('213');
      }
      $transaction->commit();
      return ['code' => 200];
    } catch (Exception $e) {
      $transaction->rollBack();
      return ['code' => -200, 'msg' => $e->getMessage()];
    }

  }

  /**
   * 摇奖
   * @return array|string
   * @throws \Exception
   */
  public function actionGetPrize()
  {
    if (Yii::$app->request->isPost) {
      Yii::$app->response->format = Response::FORMAT_JSON;
      try {

        $session = \Yii::$app->session->get('user_info');
        $is_ok = $this->CheckPrize($session->open_id);
        if ($is_ok['code'] == 200) {
          //开始摇奖
          $connection = ActivityPrize::getDb();
          $transaction = $connection->beginTransaction();
          try {
            // 判断是否有奖品可以抽
            $sql = 'SELECT SUM(prize_num) as prize_count FROM activity_prize FOR UPDATE';
            $command = $connection->createCommand($sql);
            $prize_count = $command->queryOne();

            if ($prize_count['prize_count'] == 0) {
              throw new Exception('213');
            }

            $prize = ActivityPrize::find()->where(['>', 'prize_num', 0])->asArray()->all();
            $rid = UtilService::getRand($prize); //根据概率获取奖项ID
            $rid['avatar'] = $session->avatar;
            $rid_type = explode('_', $rid['type']);
            if (!$rid['type']) {
              throw new Exception('-200');
            }
            //当获奖 $rid_type == '折扣券'是在store_information表随机取出一个奖品
            $store = new StoreInformaction();
            if ($rid_type[0] == 'coupons') {
              $store_id = mt_rand(1, 15);
              // $store_id = 1;
              $store_info = $store->getStore($store_id);
              $rid['store_info'] = $store_info;
            }
            if ($rid_type[0] == 'hongbao') {
              //发送红包
              $result = $this->SetPrize($session->open_id, $rid['prize_money']);
              if ($result['result_code'] != 'SUCCESS') {
                throw new Exception('-200');
              }
            }
            //如果中奖，修改其相对的奖品数量
            if ($rid['type']) {
              $prize_now_arr = ActivityPrize::find()->where(['id' => $rid['id']])->one();
              $prize_now_arr->prize_num = $prize_now_arr->prize_num - 1;
              $prize_now_arr->update_time = time();
              $prize_now_arr->save(0);
              //修改store_information表中数据
              if ($rid_type[0] == 'coupons') {
                $store->editStore($rid['store_info']['id']);
              }
            }

            //写摇奖数据表中
            $yaojiang_record = new YaojiangRecord();
            $yaojiang_record->ip = UtilService::getIP();
            $yaojiang_record->open_id = $session->open_id;
            $yaojiang_record->nickname = $session->nickname;
            if ($rid['type']) {
              $yaojiang_record->is_winning = 1;
              //获取用户获奖类型
              $temp_arr = $rid['type'];
              $temp_type = $this->getPrizeType($temp_arr);
              $yaojiang_record->prize = $temp_type;
              if ($yaojiang_record->prize == 7) {
                $yaojiang_record->store_id = $rid['store_info']['id'];
              }
              $hongbao_arr = [1, 2, 3, 4, 5, 6];
              if (in_array($temp_type, $hongbao_arr) == true) {
                $yaojiang_record->is_receive = 1;
              }
            }
            $yaojiang_record->update_time = time();
            $yaojiang_record->create_time = time();
            if ($yaojiang_record->save(0)) {
              $member_info = Member::find()->where(['open_id' => $session->open_id])->one();
              $member_info->yaojiang_count = 1;
              $member_info->lastlogin_time = time();
              $member_info->save(0);
              $transaction->commit();
              if ($yaojiang_record->prize == 7) {
                return ['code' => 200, 'data' => ['store_info' => $rid['store_info'], 'avatar' => $rid['avatar'], 'msg' => '202']];
              } else {

                return ['code' => 200, 'data' => ['hongbao' => $rid['prize_money'], 'avatar' => $rid['avatar'], 'msg' => '201']];
              }
            }

          } catch (Exception $e) {
            $transaction->rollBack();
            return ['code' => -200, 'msg' => $e->getMessage()];
          }

        } else {
          throw new Exception($is_ok['msg']);
        }


      } catch (Exception $e) {
        return ['code' => -200, 'msg' => $e->getMessage()];
      }
    }
  }

  public function actionPrizeList()
  {
    $user_info = Yii::$app->session->get('user_info');
    try {
      if ($user_info) {
        $prize_info = YaojiangRecord::find()->joinWith('store')->where(['open_id' => $user_info['open_id']])->asArray()->all();
        return ['code' => 200, 'data' => $prize_info];
      }
    } catch (Exception $e) {
      return ['code' => -200, 'msg' => $e->getMessage()];
    }
  }

  public function actionMyPrize()
  {
//    if (Yii::$app->session->get('user_info')) {
//      $prize_id = Yii::$app->request->get('id', 0);
//      if ($prize_id) {
//        $prize_info = YaojiangRecord::find()->joinWith('store')->where(['yaojiang_record.id' => $prize_id])->asArray()->one();
//        $js_info = RequestService::jsapi_ticket_config(RequestService::GetUrl(true));
//        return $this->render('myprize', ['info' => $prize_info, 'js_info' => $js_info]);
//      }
//    } else {
//      return $this->redirect('/weixin/activity/index');
//    }
    if (Yii::$app->request->isAjax) {
      Yii::$app->response->format = Response::FORMAT_JSON;
      try {
        $user_info = Yii::$app->session->get('user_info');
        $member_info = Member::find()->where(['open_id' => $user_info->open_id])->asArray()->one();
        if (!$member_info) {
          return ['code' => -200, 'msg' => -200];
        }
        $prize_info = YaojiangRecord::find()->joinWith('store')->where(['yaojiang_record.open_id' => $user_info->open_id])->asArray()->one();
        $prize_info['avatar'] = $user_info->avatar;
        if ($prize_info['prize'] != '7') {
          unset($prize_info['store']);
          $prize_info['hongbao'] = (StaticServices::getHongbao())[$prize_info['prize']];
        }
        return ['code' => 200, 'data' => $prize_info];
      } catch (Exception $e) {
        return ['code' => -200, 'msg' => $e->getMessage()];
      }
    }
  }

  /**
   * 核销
   * @return array
   */
  public function actionCash()
  {
    if (Yii::$app->request->isAjax) {
      Yii::$app->response->format = Response::FORMAT_JSON;
      try {
        $verfiy_code = '909388';
        $code = \Yii::$app->request->post('code', '');
        $prize_id = Yii::$app->request->post('id', 0);
        if (empty($code)) {
          throw new Exception('请填写核销码');
        }
        $session = Yii::$app->session->get('user_info');
        if ($code == $verfiy_code) {
          $prize_info = YaojiangRecord::find()->where(['open_id' => $session->open_id, 'id' => $prize_id])->andWhere(['is_winning' => 1, 'prize' => 7])->one();
          if ($prize_info) {
            $prize_info->is_receive = 1;
            $prize_info->update_time = time();
            $prize_info->save(0);
            return ['code' => 200, 'msg' => '核销成功'];
          } else {
            throw new Exception('数据有误');
          }

        }

      } catch (Exception $e) {
        return ['code' => -200, 'msg' => $e->getMessage()];
      }

    }
  }

  /**
   * 更新用户信息
   * @return array
   */
  public function actionUpdateMember()
  {
    if (Yii::$app->request->isAjax) {
      Yii::$app->response->format = Response::FORMAT_JSON;
      try {
        $session = Yii::$app->session->get('user_info');
        if (!$session->open_id) {
          throw new Exception('系统正忙,请稍后再试');
        }
        $member_name = Yii::$app->request->post('member_name');
        $member_phone = Yii::$app->request->post('member_phone');
        if (!$member_name || !$member_phone) {
          throw new Exception('参数不正确');
        }
        if (!preg_match('/^(0|86|17951)?(1[356789])[0-9]{9}$/', $member_phone)) {
          throw new Exception('请输入正确的电话号码');
        }
        $member_info = Member::find()->where(['open_id' => $session->open_id])->one();
        if (!$member_info) {
          throw new Exception('数据有误');
        }
        $member_info->member_name = $member_name;
        $member_info->member_phone = $member_phone;
        $member_info->lastlogin_time = time();
        $member_info->save(0);
        return ['code' => 200, 'msg' => '更新成功'];

      } catch (Exception $e) {
        return ['code' => -200, 'msg' => $e->getMessage()];
      }
    }
  }

  /**
   * 判断是否更新用户数据
   * @return array
   */
  public function actionHasUpdate()
  {
    if (Yii::$app->request->isAjax) {
      Yii::$app->response->format = Response::FORMAT_JSON;
      try {
        if (!UtilService::isWechat()) {
          return ['code' => -200, 'msg' => '请在微信中打开'];
        }
        $session = Yii::$app->session->get('user_info');
        if (!$session->open_id) {
          throw new Exception('参数有误');
        }
        $member_info = Member::find()->where(['open_id' => $session->open_id])->one();
        if (!$member_info) {
          throw new Exception('数据有误');
        }
        if (!$member_info->member_phone || !$member_info->member_name) {
          return ['code' => 200, 'type' => -1];
        }
        return ['code' => 200, 'type' => 1];
      } catch (Exception $e) {
        return ['code' => -200, 'msg' => $e->getMessage()];
      }
    }
  }

  private function SetPrize($openid, $amount)
  {
    $rtime = time();
    $weixin_info = \Yii::$app->params['weixin'];
    $mch_billno = $weixin_info['wxPay_mch_id'] . date('YmdHis', $rtime) . rand(1000, 9999);
    $nonce_str = md5(UtilService::getRandChar(10) . $rtime);
    $__construct = [
        'nonce_str'    => $nonce_str,
        'mch_billno'   => $mch_billno, //商户订单号
        'mch_id'       => $weixin_info['wxPay_mch_id'], //商户号
        'wxappid'      => $weixin_info['appid'], //公众账号appid
        'send_name'    => $weixin_info['wxPay_name'], //商户名称
        're_openid'    => $openid, //用户openid
        'total_amount' => $amount * 100, //付款金额，单位分
        'total_num'    => 1, //红包发放总人数
        'wishing'      => '恭喜您摇到了' . $amount . '元红包', //红包祝福语
        'client_ip'    => '101.132.33.13', //调用接口的机器Ip地址
        'act_name'     => '苏州环球港', //活动名称
        'remark'       => '', //备注信息
    ];
    ksort($__construct);
    $string = UtilService::ToUrlParams($__construct);
    //签名步骤二：在string后加入KEY
    $string = $string . '&key=' . $weixin_info['wxPay_key'];
    //签名步骤三：MD5加密
    $string = md5($string);
    $__construct['sign'] = strtoupper($string);
    $xml = UtilService::ToXml($__construct);
//        $startTimeStamp = self::getMillisecond(); //请求开始时间
    $response = UtilService::postXmlCurl($xml, 'https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack', true, 10);
    $result = UtilService::FromXml($response);

    //self::reportCostTime($url, $startTimeStamp, $result);//上报请求花费时间
    $hongbao_log = new HongbaoLog();
    $hongbao_log->open_id = \Yii::$app->session->get('user_info')->open_id;
    $hongbao_log->account = $amount . '元';
    $hongbao_log->return_code = $result['return_code'];
    $hongbao_log->return_msg = $result['return_msg'];
    $hongbao_log->result_code = $result['result_code'];
    $hongbao_log->result_msg = json_encode($result);
    $hongbao_log->create_time = time();
    $hongbao_log->save(0);

    return $result;

  }

  private function get_curr_time_section($nowStr, $beginStr = '11:00', $endStr = '22:00')
  {
    $checkDayStr = date('Y-m-d', $nowStr);
    $timeBegin = strtotime($checkDayStr . $beginStr);
    $timeEnd = strtotime($checkDayStr . $endStr);

    if ($nowStr >= $timeBegin && $nowStr < $timeEnd) {
      return 'begin';
    }
    if ($nowStr < $timeBegin) {
      return 'no_begin';
    }
    if ($nowStr >= $timeEnd) {
      return 'is_end';
    }
  }

  private function getPrizeType($option)
  {
    $prize_type = ConstantMapServices::$prize_type;
    foreach ($prize_type as $key => $value) {
      if ($option == $key) {
        return $value;
      }
    }
  }


}
